// 模拟数据请求
// import '@/utils/mock'
// import {getInfo} from '@/api/user'

import { ref } from "vue";

export default function initData(props) {
  
  /*const props = defineProps({
    parentData: {
      type: [Array, Object, String, Number],
      default: ()=> null
    },
    config: {
      type: Object,
      default: ()=> ({})
    }
  });*/
  const requestData = ref(null);
  
  function getData() {
    return new Promise((resolve, reject)=> {
      // chart组件传递数据
      if(props.data) {
        const resData = JSON.parse(JSON.stringify(props.data))
        requestData.value = resData
        resolve(resData);
      }
      // chart组件传 chartId
      else if(props.chartId) {
        
        const resData = {
          source: [
            ['product', '2015', '2016', '2017'],
            ['Matcha Latte', 43.3, 85.8, 93.7],
            ['Milk Tea', 83.1, 73.4, 55.1],
            ['Cheese Cocoa', 86.4, 65.2, 82.5],
            ['Walnut Brownie', 72.4, 53.9, 39.1]
          ]
        }
        
        requestData.value = resData
        resolve(resData)
  
        /*getInfo().then(res=> {
          resolve(res);
        }).catch(err=> {
          reject(err);
        });*/
      }
      else {
        requestData.value = null
        resolve(null);
      }
    })
  }
  
  // 根据字符串获取 requestData 的值
  // 如：requestData = {a: [{b: 1}]}, getVal('a.0.b') 输出 1
  // selector: String, 非String且非空值时直接返回requestData
  // defaultVal: 匹配不到值时的默认值
  function getVal(selector, defaultVal = 0) {
    return typeof selector === 'string' && selector ?
      selector
        .replace(/\[([^[\]]*)]/g, '.$1')
        .split('.')
        .reduce((prev, cur) => prev && prev[cur], this.requestData) ?? defaultVal
      : requestData.value;
  }
  
  return {
    requestData,
    getData,
    getVal
  }
  
}